﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Linq;
using G;
using System.Diagnostics;

namespace G.Net
{
    public class WebUtil
    {

        public WebUtil()
        {

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="callback"></param>
        /// <param name="querydata">query参数，无需做UrlEncode处理</param>
        /// <param name="header"></param>
        public static void DoGet(string url, string path = null, Action<WebExceptionStatus, string> callback = null, IDictionary<string, string> querydata = null, Dictionary<string, string> header = null)
        {
            DoGet(CreateUri(url, querydata, path), callback, header);
        }

        public static void DoGet(Uri url, Action<WebExceptionStatus, string> callback = null, IDictionary<string, string> header = null)
        {
            var request = CreateWebRequest(RequestMethod.GET, url, header);

            if (Debugger.IsAttached)
            {
                Debug.WriteLine("请求地址：" + request.RequestUri.OriginalString);
            }
            request.BeginGetResponse((i) =>
            {
                try
                {
                    var response = request.EndGetResponse(i);
                    using (var stream = response.GetResponseStream())
                    {
                        using (var streamReader = new System.IO.StreamReader(stream))
                        {
                            callback(WebExceptionStatus.Success, streamReader.ReadToEnd());
                        }
                    }
                }
                catch (WebException ex)
                {
                    if (callback != null)
                        callback(ex.Status, ex.Message);
                    else
                        throw ex;
                }
            }, null);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="callBack"></param>
        /// <param name="querydata">query参数，无需做UrlEncode处理</param>
        /// <param name="postData">需求post到服务器的数据</param>
        /// <param name="header"></param>
        public static void DoPost(string url, string path = null, Action<WebExceptionStatus, string> callBack = null, IDictionary<string, string> querydata = null, byte[] postData = null, Dictionary<string, string> header = null)
        {
            DoPost(CreateUri(url, querydata, path), callBack, postData, header);
        }
        public static void DoPost(Uri url, Action<WebExceptionStatus, string> callBack = null, byte[] postData = null, IDictionary<string, string> header = null)
        {
            var request = CreateWebRequest(RequestMethod.POST, url, header);
            request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            request.BeginGetRequestStream((i) =>
            {
                try
                {
                    var responseStream = request.EndGetRequestStream(i);
                    if (postData != null)
                        responseStream.Write(postData, 0, postData.Length);
                    responseStream.Close();
                }
                catch (WebException ex)
                {
                    if (callBack != null)
                        callBack(ex.Status, ex.Message);
                    else
                        throw ex;
                }
                request.BeginGetResponse((_i) =>
                {
                    try
                    {
                        var response = request.EndGetResponse(_i);
                        using (var stream = response.GetResponseStream())
                        {
                            using (var streamReader = new System.IO.StreamReader(stream))
                            {
                                callBack(WebExceptionStatus.Success, streamReader.ReadToEnd());
                            }
                        }
                    }
                    catch (WebException ex)
                    {
                        if (callBack != null)
                            callBack(ex.Status, ex.Message);
                        else
                            throw ex;
                    }
                }, null);
            }, null);
        }


        /// <summary>
        /// 根据url和query参数组合成一个uri,queryString经过UrlEncode编码
        /// </summary>
        /// <param name="url"></param>
        /// <param name="querydata"></param>
        /// <returns></returns>
        public static Uri CreateUri(string url, IDictionary<string, string> querydata, string path = null)
        {
            UriBuilder builder = new UriBuilder(url);
            if (path != null)
                builder.Path = path;
            if (querydata != null && querydata.Count > 0)
            {
                builder.Query = String.Join("&", from c in querydata
                                                 select string.Format("{0}={1}", c.Key, c.Value));
            }
            return new Uri(builder.Uri.AbsoluteUri, UriKind.Absolute);
        }

        public static HttpWebRequest CreateWebRequest(RequestMethod method, Uri uri, IDictionary<string, string> header = null)
        {
            HttpWebRequest request = WebRequest.CreateHttp(uri);

            if (header != null)
            {
                foreach (var item in header)
                {
                    if (item.Value != null)
                        request.Headers[item.Key] = item.Value;
                }
            }
            switch (method)
            {
                case RequestMethod.GET:
                    request.Method = "GET";
                    break;
                case RequestMethod.POST:
                    request.Method = "POST";
                    break;
                default:
                    throw new ArgumentException("不支持该类型的请求的方式，只支持Get和Post");
            }
            return request;
        }



    }
}
